package com.ldc.login.viewodel

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.reflect.TypeToken
import com.ldc.commonlibs.common.RspModel
import com.ldc.commonlibs.common.ViewModelBase
import com.ldc.commonlibs.conf.RouteConf
import com.ldc.commonlibs.http.HttpServer
import com.ldc.commonlibs.model.LoginModel
import com.ldc.commonlibs.uts.DataStoreUts
import com.ldc.commonlibs.uts.JsonUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import retrofit2.Response
import java.lang.reflect.Type

class LoginViewModel : ViewModelBase() {

    private val apiService: HttpServer = getServer(HttpServer::class.java)

    private val loginModel = MutableLiveData<RspModel<LoginModel>>()

    // 登录
    fun login(uname: String, pass: String) = viewModelScope.launch {
        val response: Response<ResponseBody> = withContext(Dispatchers.IO) {
            apiService.login(
                hashMapOf(
                    "username" to uname,
                    "password" to pass,
                )
            )
        }
        if (200 == response.code() && response.isSuccessful) {
            val jsonData = response.body()!!.string()
            if (TextUtils.isEmpty(jsonData)) return@launch
            val type: Type = object : TypeToken<RspModel<LoginModel>>() {}.type
            val data: RspModel<LoginModel> = JsonUtils.jsonToBeanByType(
                jsonData,
                type
            )
            loginModel.value = data
            loginSuccess(uname, pass)
            nextAction()
        }

    }

    /**
     * 登录成功
     */
    private fun loginSuccess(username: String, password: String) {
        DataStoreUts.INSTANCE.apply {
            setIsLogin(true)
            setUserName(username)
            setUserPassWord(password)
        }
    }

    private fun nextAction() {
        ARouter.getInstance()
            .build(RouteConf.FrameworkRoute.startEnter)
            .navigation()
    }

}